<?php
namespace app\admin\controller;

use app\BaseController;
use app\Request;
use think\facade\Db;
use think\facade\Session;
use think\Image;


class ApiAdmin extends BaseController
{
    
    protected $model = null;
    protected $with = [];
    protected $datasArray = null;

    public function initialize(){
        $this->model = new \app\admin\model\SystemAdmin;
        $this->with = ['systemauth'];
    }
    
    protected $middleware = [
        \app\admin\middleware\Check::class => ['except' =>['login']]
    ];

    public function login(Request $request)
    {
        $username = trim(input('username'));
        $password = trim(input('password'));
        $u = Db::table('gms_system_admin')->where('username',$username)->find();
        if($u)
        { 
            if($u['password'] === md5Pass($password,$u['salt']))
            {
                Session::set('userinfo',[
                    "user_id" => $u["id"],
                    "username" => $u["username"],
                ]);
                return $this->success("登陆成功");
            }else
            {
                return $this->error("密码错误");
            }
        }
        else{
            return $this->error("用户名或者密码错误");
        }
    }

    public function add(){
        
        $salt = randomSalt();
        $password = input('passowrd');
        $password = md5Pass($password, $salt);
        $this->datasArray = [
            "salt" => $salt,
            "password" => $password,
        ];
        return parent::add();
    }

    public function edit(){
        
        $salt = randomSalt();
        $password = input('passowrd');
        $password = md5Pass($password, $salt);
        $this->datasArray = [
            "salt" => $salt,
            "password" => $password,
        ];
        return parent::edit();
    }
    public function uploadImg(Request $request)
    {
        $maxWidth = config('app.max_width');
        $maxHeight = config('app.max_height');

        $file = $request->file('file');
        $filename = \think\facade\Filesystem::disk('public')->putFile( 'uploads', $file);
        $filename = str_replace("\\","/",$filename);

        $imagefile = root_path() .'public/' . $filename;
        $imagefile = str_replace("\\","/",$imagefile);
        $image = Image::open($imagefile);
        //dd($image);
        $image->thumb($maxWidth, $maxHeight)->save($imagefile);
        $filesize = filesize($imagefile);
        $image = Image::open($imagefile);
        //存入上传文件管理数据表
        $data =[
            'upload_type'   => 'local',
            'original_name' => 'GMS_WEB',
            'mime_type'     => $image->mime(),
            'image_width'  => $image->width(),
            'image_height'  => $image->height(),
            'image_type'   => $image->type(),
            'file_size'     => $filesize,
            'file_ext'      => strtolower($file->getOriginalExtension()),
            'url'           => '/' . $filename,
            'create_time'   => time(),
         ];
        DB::name('SystemUploadfile')->save($data);
        return $this->success($filename);
    }

    /**
     * 修改密码
     * 
     */
    public function changePass()
    {
        $datas = $this->request->param();
        try {
            $this->validate($datas, 'Changepass');
        } catch (\Throwable $th) {
            return $this->error($th->getMessage()) ;
        }
        $userinfo = $this->request->userinfo;
        $user = $this->model->where('id',$userinfo['user_id'])->find();
        $oldpass = md5Pass($datas['oldpass'], $user['salt']);

        if ($oldpass == $user['password']) {
            $newsalt = randomSalt();
            $newpass = md5Pass($datas["newpass"],$newsalt);
            $res = $this->model->where('id',$userinfo['user_id'])->update([
                "password" => $newpass,
                "salt" => $newsalt
            ]);
            if ($res) {
                return $this->success("密码修改成功",$res) ;
            } else {
                return $this->error("密码修改失败",$res) ;
            }
            
        } else {
            return $this->error("输入的旧密码不正确") ;
        }
        
    }
}